package com.leyou.user.controller;

import com.leyou.user.pojo.User;
import com.leyou.user.serivce.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据是否可用，type=1校验用户名，type=2校验手机号
     *
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUser(@PathVariable String data, @PathVariable Integer type) {

        Boolean result = userService.checkUser(data, type);
        if (result == null) {
            return ResponseEntity.badRequest().build();
        }
        //可用true，不可以false 无论可用不可以都要返回
        return ResponseEntity.ok(result);
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam String phone) {
        userService.sendVerifyCode(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 注册
     */
    @PostMapping("/register")   //对象接收普通参数不需要@RequestBody
    public ResponseEntity<Void> register(@Valid User user, @RequestParam String code) {
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 登陆
     */
    @GetMapping("/query")
    public ResponseEntity<User> queryUser(@RequestParam String username, @RequestParam String password) {
        User user = userService.queryUser(username, password);
        if (user == null) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(user);
    }

}
